package sk.hackcraft.multibox.server.net;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.json.JSONObject;

import sk.nixone.http.Servlet;
import sk.nixone.http.ServletExchange;

import sk.hackcraft.multibox.server.net.Server;

abstract public class JSONServlet extends Servlet {
	static public abstract class ResultException extends RuntimeException {
		public ResultException(String message) {
			super(message);
		}
		
		abstract public String getResultType();
	}
	
	static public enum Method {
		GET, POST
	}
	
	static private Logger logger = Logger.getLogger(JSONServlet.class.getName());
	
	final protected Server server;
	
	public JSONServlet(Server server) {
		this.server = server;
	}
	
	@Override
	final public Object doGet(ServletExchange exchange) {
		return doMethod(exchange, Method.GET);
	}
	
	@Override
	final public Object doPost(ServletExchange exchange) {
		return doMethod(exchange, Method.POST);
	}
	
	final public Object doMethod(ServletExchange exchange, Method method) {
		JSONObject response = new JSONObject();
		try {
			JSONObject methodResponse = doRequest(method, exchange, response);
			
			if(methodResponse == null) {
				response.put("result", "ERROR");
				logger.warning("Method on a resource is not implemented.");
			} else if(methodResponse != response) {
				response.put("result", "ERROR");
				logger.severe("Internal server error.");
			} else {
				response.put("result", "OK");
			}
		} catch(ResultException exception) {
			response.put("result", exception.getResultType());
		} catch(Throwable cause) {
			logger.log(Level.SEVERE, cause.getMessage(), cause);
			response.put("result", "ERROR");
		}
		return response.toString();
	}
	
	public JSONObject doRequest(Method method, ServletExchange exchange, JSONObject response) {
		// overridable
		return null;
	}
}
